#include "stdafx.h"
#include "SqliteTypeUtil.h"
#include "sqlite3.h"
#include <vector>

#ifdef WIN32
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif

namespace serika
{
	namespace db
	{
		SqliteTypeUtil::SqliteTypeUtil()
		{
		}

		SqliteTypeUtil::~SqliteTypeUtil()
		{
		}

		void SqliteTypeUtil::InsertValue(sqlite3_stmt* stmt, FieldMap* fm)
		{
			int columnCount = sqlite3_column_count(stmt);
			for (int col = 0; col < columnCount; ++col)
			{
				SqliteTypeUtil::InsertValue(col, stmt, fm);
			}
		}

		void SqliteTypeUtil::InsertValue(int col, sqlite3_stmt* stmt, FieldMap* fm)
		{
			std::string colName = sqlite3_column_name(stmt, col);

			int type = sqlite3_column_type(stmt, col);
			switch (type)
			{
			case SQLITE_INTEGER:
				fm->insert(std::make_pair(colName, Any(sqlite3_column_int(stmt, col))));
				break;

			case SQLITE_FLOAT:
				fm->insert(std::make_pair(colName, Any(sqlite3_column_double(stmt, col))));
				break;

			case SQLITE_TEXT:
				{
					const unsigned char* str = sqlite3_column_text(stmt, col);
					int len = sqlite3_column_bytes(stmt, col);
					std::string s(reinterpret_cast<const char*>(str), len);
					fm->insert(std::make_pair(colName, Any(ut::StringHelper::Convert(s))));
				}
				break;

			case SQLITE_BLOB:
				{
					const unsigned char* buf = static_cast<const unsigned char*>(sqlite3_column_blob(stmt, col));
					int len = sqlite3_column_bytes(stmt, col);
					std::vector<unsigned char> blob(buf, buf+len);
					fm->insert(std::make_pair(colName, Any(blob)));
				}
				break;

			case SQLITE_NULL:
			default:
				fm->insert(std::make_pair(colName, NIL));
			}
		}
	}
}
